<?php
/**
 * This controller is uses to proccess book
 *
 * @author	huytbt
 * @date	2012-04-23
 * @version	1.0
 */
class BookController extends HController
{
	// Set action default for this controller
	public $defaultAction = 'list';
	
	/**
	 * This action is uses to display list book of department
	 */
	public function actionList($department_id, $search = '', $course_id = 0, $page_size = 5)
	{
		Yii::import('application.modules.user.models.User');
		
		// Get department
		Yii::import('application.modules.textbooks.models.TextbookDepartment');
		$department = TextbookDepartment::model()->findByPk($department_id);
		// If does not exists department then redirect user return back page
		if (!$department) $this->redirect(array('/textbooks/department'));
		
		// Get university of department
		Yii::import('application.modules.textbooks.models.TextbookUniversity');
		$university = $department->university;
		
		if (isset($_POST['course_id'])) $course_id = $_POST['course_id'];
		if (isset($_POST['search'])) $search = $_POST['search'];
		
		if ($course_id == 0) {
			// Get all courses of department
			$courses = $department->courses;
		} else {
			Yii::import('application.modules.textbooks.models.TextbookCourse');
			$courses = array(TextbookCourse::model()->findByPk($course_id));
		}
		
		// Pagination
		$pages = new CPagination;
		$pages->pageSize = $page_size;
		
		// Get all books of courses
		Yii::import('application.modules.textbooks.models.TextbookBook');
		$books = TextbookBook::model()->getBooksByCourses($courses, $search, $pages);
		
		// Register assets
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets');
		Yii::app()->clientScript->registerScriptFile($baseScriptUrl . '/js/jquery.h.textbooks.book.js');
		
		$this->render('list', array(
			'course_id' => $course_id,
			'university' => $university,
			'department' => $department,
			'courses' => $courses,
			'books' => $books,
			'search' => $search,
			'pages' => $pages,
		));
	}
	
	/**
	 * This action is used to view book details
	 */
	public function actionDetails($book_id)
	{
		Yii::import('application.modules.user.models.User');
		
		Yii::import('application.modules.textbooks.models.TextbookBook');
		$book = TextbookBook::model()->findByPk($book_id);
		if (!$book) $this->redirect(array('/textbooks/department'));
		
		$course = $book->course;
		$department = $course->department;
		$university = $department->university;
			
		$this->render('details', array(
			'university' => $university,
			'department' => $department,
			'course' => $course,
			'book' => $book,
		));
	}
	
	/**
	 * This action is used to post book
	 */
	public function actionPost($university_id = 0, $department_id = 0)
	{
		// Get current user
		Yii::import('application.modules.user.models.User');
		$user = User::model()->findByPk(Yii::app()->user->id);
		if (!$user) throw new Exception('User does not exists. Please relogin.');
		
		if ($university_id != 0) {
			Yii::import('application.modules.textbooks.models.TextbookUniversity');
			$university = TextbookUniversity::model()->findByPk($university_id);
		} else {
			if ($department_id != 0) {
				Yii::import('application.modules.textbooks.models.TextbookDepartment');
				$department = TextbookDepartment::model()->findByPk($department_id);
				if ($department) $university = $department->university;
			} else {
				// Get the first university of user
				Yii::import('application.modules.textbooks.models.TextbookUniversity');
				$universities = $user->universities;
				
				if ($universities)
					$university = $user->universities[0]->university;
			}
		}
		
		if (!isset($university) || $university == null) throw new Exception('Does not exists university.');
		
		// Post book
		Yii::import('application.modules.textbooks.models.TextbookBook');
		$model = new TextbookBook;
		if(isset($_POST['TextbookBook'])) {
			$model->attributes = $_POST['TextbookBook'];
			$model->user_id = $user->id;
			$model->created = time();
			$model->university_id = $university->id;
			if ($model->validate()) {
				// Check course exists?
				$course_name = $model->course_id;
				Yii::import('application.modules.textbooks.models.TextbookCourse');
				$course = TextbookCourse::model()->findByAttributes(array(
					'name' => $course_name,
					'department_id' => $model->department_id,
				));
				
				if (!$course) {
					$course = new TextbookCourse;
					$course->name = $course_name;
					$course->department_id = $model->department_id;
					if (!$course->save())
						throw new Exception('Cannot save course.');
				}
				$model->course_id = $course->id;
				// Upload image
				$model->image = CUploadedFile::getInstance($model, 'image');
				if ($model->image) {
					$strFilename = time() . '_' . $model->image;
					$uploadPath = Yii::getPathOfAlias('webroot') . Yii::app()->getModule('textbooks')->strBookUploadPath;
					@mkdir($uploadPath, 777, true);
					$model->image->saveAs($uploadPath . '/' . $strFilename);
					$model->image = $strFilename;
					
					// Create thumbnail
					@mkdir($uploadPath . '/thumbs', 777, true);
					Yii::import("ext.EPhpThumb.EPhpThumb");
					$thumb = new EPhpThumb();
					$thumb->init(); //this is needed
					$thumb->create($uploadPath . '/' . $strFilename)
						  ->adaptiveResize(Yii::app()->getModule('textbooks')->widthThumb, Yii::app()->getModule('textbooks')->heightThumb)
						  ->save($uploadPath . '/thumbs/' . $strFilename);
				}
				
				if ($model->save()) {
					// Increase books number for cache
					$course->books = $model->countBooks($course->id);
					$course->save();
					Yii::import('application.modules.textbooks.models.TextbookDepartment');
					$department = $course->department;
					$department->books = $model->countBooks(null, $department->id);
					$department->save();
					
					// Add course taken for user
					Yii::import('application.modules.textbooks.models.TextbookUserCourse');
					$userCourse = TextbookUserCourse::model()->countByAttributes(array(
						'course_id' => $course->id,
						'user_id' => $user->id,
						'type' => TextbookUserCourse::TYPE_TAKEN,
					));
					if (!$userCourse) {
						$userCourse = new TextbookUserCourse;
						$userCourse->attributes = array(
							'course_id' => $course->id,
							'user_id' => $user->id,
							'type' => TextbookUserCourse::TYPE_TAKEN,
						);
						$userCourse->save();
					}
					
					$this->redirect(array('/textbooks/book/list', 'department_id'=>$department->id));
				}
			}
		} else {
			$model->department_id = $department_id;
			$model->email = $user->email;
		}
		
		// Select all departments of current university
		Yii::import('application.modules.textbooks.models.TextbookDepartment');
		if ($university)
			$departments = $university->departments;
		else
			$departments = TextbookDepartment::model()->getDepartmentsByUniversity($university->id);
		
		// Register assets
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets');
		Yii::app()->clientScript->registerScriptFile($baseScriptUrl . '/js/jquery.h.textbooks.book.js');
		Yii::app()->clientScript->registerScriptFile($baseScriptUrl . '/js/jquery.h.textbooks.course.js');
		
		$this->render('post', array(
			'model' => $model,
			'user' => $user,
			'university' => $university,
			'departments' => $departments,
			'department_id' => $department_id,
		));
	}

	/**
	 * This action is used to manage books of current user
	 */
	public function actionManage()
	{
		$model = new TextbookBook('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TextbookBook']))
			$model->attributes=$_GET['TextbookBook'];
		$model->user_id = Yii::app()->user->id;

		$this->render('manage',array(
			'model' => $model,
		));
	}

	/**
	 * This action is used to edit a book
	 */
	public function actionEdit($book_id, $university_id = 0, $department_id = 0)
	{
		// Get current user
		Yii::import('application.modules.user.models.User');
		$user = User::model()->findByPk(Yii::app()->user->id);
		if (!$user) throw new Exception('User does not exists. Please relogin.');
		
		if ($university_id != 0) {
			Yii::import('application.modules.textbooks.models.TextbookUniversity');
			$university = TextbookUniversity::model()->findByPk($university_id);
		} else {
			if ($department_id != 0) {
				Yii::import('application.modules.textbooks.models.TextbookDepartment');
				$department = TextbookDepartment::model()->findByPk($department_id);
				if ($department) $university = $department->university;
			} else {
				// Get the first university of user
				Yii::import('application.modules.textbooks.models.TextbookUniversity');
				$universities = $user->universities;
				
				if ($universities)
					$university = $user->universities[0]->university;
			}
		}
		
		if (!isset($university) || $university == null) throw new Exception('Does not exists university.');
		
		$model = TextbookBook::model()->findByAttributes(array(
			'id' => $book_id,
			'user_id' => Yii::app()->user->id,
		));

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['TextbookBook']))
		{
			$oldCourse = $model->course_id;
			$oldDepartment = $model->department_id;
			$model->attributes = $_POST['TextbookBook'];
			$newDepartment = $model->department_id;
			
			// Check course exists?
			$course_name = $model->course_id;
			Yii::import('application.modules.textbooks.models.TextbookCourse');
			$course = TextbookCourse::model()->findByAttributes(array(
				'name' => $course_name,
				'department_id' => $model->department_id,
			));
			
			if (!$course) {
				$course = new TextbookCourse;
				$course->name = $course_name;
				$course->department_id = $model->department_id;
				if (!$course->save())
					throw new Exception('Cannot save course.');
			}
			$model->course_id = $course->id;
			$newCourse = $model->course_id;
			
			if($model->save()) {
				if ($oldCourse != $newCourse) {
					// Update books number for cache
					Yii::import('application.modules.textbooks.models.TextbookCourse');
					$course = TextbookCourse::model()->findByPk($oldCourse);
					$course->books = $model->countBooks($oldCourse);
					$course->save();
					
					$course = TextbookCourse::model()->findByPk($newCourse);
					$course->books = $model->countBooks($newCourse);
					$course->save();
				}
				if ($oldDepartment != $newDepartment) {
					// Update books number for cache
					Yii::import('application.modules.textbooks.models.TextbookDepartment');
					$department = TextbookDepartment::model()->findByPk($oldDepartment);
					$department->books = $model->countBooks(null, $oldDepartment);
					$department->save();
					
					$department = TextbookDepartment::model()->findByPk($newDepartment);
					$department->books = $model->countBooks(null, $newDepartment);
					$department->save();
				}
				$this->redirect(array('/textbooks/book/details','book_id'=>$model->id));
			}
		}
		
		// Select name course (not id)
		Yii::import('application.modules.textbooks.models.TextbookCourse');
		$course = TextbookCourse::model()->findByPk($model->course_id);
		$model->course_id = $course->name;

		// Select all departments of current university
		Yii::import('application.modules.textbooks.models.TextbookDepartment');
		if ($university)
			$departments = $university->departments;
		else
			$departments = TextbookDepartment::model()->getDepartmentsByUniversity($university->id);

		$this->render('edit',array(
			'model' => $model,
			'departments' => $departments,
		));
	}

	/**
	 * This action is used to delete a book
	 */
	public function actionDelete($book_id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = TextbookBook::model()->findByAttributes(array(
				'id' => $book_id,
				'user_id' => Yii::app()->user->id,
			));

			if ($model && $model->delete()) {
				// Update books number for cache
				Yii::import('application.modules.textbooks.models.TextbookCourse');
				$course = $model->course;
				$course->books = $model->countBooks($course->id);
				$course->save();
				Yii::import('application.modules.textbooks.models.TextbookDepartment');
				$department = $course->department;
				$department->books = $model->countBooks(null, $department->id);
				$department->save();
			}

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/textbooks/book/manage'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * This method is used to search book
	 */
	public function actionSearch($search_book = '', $page_size = 10)
	{
		if (isset($_POST['search_book'])) $search_book = $_POST['search_book'];
		
		// Get current user
		Yii::import('application.modules.user.models.User');
		$user = User::model()->findByPk(Yii::app()->user->id);
		
		// Get the first university of user
		Yii::import('application.modules.textbooks.models.TextbookUniversity');
		$universities = $user->universities;
		
		if ($universities)
			$university = $user->universities[0]->university;
		else
			$this->redirect(array('/textbooks/profile/universities'));
		
		// Pagination
		$pages = new CPagination;
		$pages->pageSize = $page_size;
		
		Yii::import('application.modules.textbooks.models.TextbookBook');
		$books = TextbookBook::model()->getBooks($search_book, $university->id, null, $pages);
		
		$this->render('search', array(
			'books' => $books,
			'pages' => $pages,
		));
	}
}
